/**

 @Name：layuiAdmin 公共业务


 @License：LPPL

 */

layui.define(function (exports) {
    var $ = layui.$
        , layer = layui.layer
        , laytpl = layui.laytpl
        , setter = layui.setter
        , view = layui.view
        , admin = layui.admin
        , table = layui.table
        , upload = layui.upload
        , element = layui.element;
    //公共业务的逻辑处理可以写在此处，切换任何页面都会执行
    /**
     * 获取Url中的参数对应的值
     * @param key
     * @returns string
     */
    window.getUrlParam = function(key) {
        let params = new URLSearchParams(window.location.search);
        return params.get(key);
    }

    /**
     * 通用打开弹窗
     * @param title
     * @param url
     * @param width
     * @param height
     * @param isFull
     */
    window.open = function (title, url, width, height, isFull) {
        const index = layer.open({
            type: 2
            ,title: title
            ,content: url
            ,maxmin: true
            ,area: [width, height]
        });
        if (isFull) {
            layer.full(index);
        }
    }

    /**
     * 通用添加弹窗
     * @param title
     * @param url
     * @param width
     * @param height
     * @param tableID
     * @param isFull
     */
    window.add = function (title, url, width, height, tableID, isFull=false) {
        const index = layer.open({
            type: 2
            ,title: title
            ,content: url + '/create'
            ,maxmin: true
            ,area: [width, height]
            ,btn: ['确定', '取消']
            ,yes: function(index, layero){
                var iframeWindow = window['layui-layer-iframe'+ index]
                    ,submitID = tableID + '-submit'
                    ,submit = layero.find('iframe').contents().find('#'+ submitID);
                //监听提交
                iframeWindow.layui.form.on('submit('+ submitID +')', function (submit) {
                    admin.req({
                        url: url
                        , data: submit.field
                        , type: "POST"
                        , done: function (res) {
                            if (res.code === 0) {
                                layer.msg(res.message, {icon: 6});
                                table.reload(tableID); //数据刷新
                                layer.close(index); //关闭弹层
                            } else {
                                layer.msg(res.message, {icon: 5});
                            }
                        }
                    });
                });
                submit.trigger('click');
            }
        });
        if (isFull) {
            layer.full(index);
        }
    }

    /**
     * 通用编辑弹窗
     * @param title
     * @param url
     * @param width
     * @param height
     * @param tableID
     * @param isFull
     */
    window.save = function (title, url, width, height, tableID, isFull=false) {
        const index = layer.open({
            type: 2
            ,title: title
            ,content: url
            ,area: [width, height]
            ,btn: ['确定', '取消']
            ,resize: false
            ,yes: function(index, layero){
                //点击确认触发 iframe 内容中的按钮提交
                var submit = layero.find('iframe').contents().find("#" + tableID + '-submit');
                submit.click();
            }
        });
        if (isFull) {
            layer.full(index);
        }
    }

    /**
     * 通用编辑弹窗
     * @param title
     * @param url
     * @param width
     * @param height
     * @param tableID
     * @param obj
     * @param isFull
     */
    window.edit = function (title, url, width, height, tableID, obj, isFull=false) {
        const index = layer.open({
            type: 2
            ,title: title
            ,content: url + '/edit'
            ,area: [width, height]
            ,btn: ['确定', '取消']
            ,resize: false
            ,yes: function(index, layero){
                var iframeWindow = window['layui-layer-iframe'+ index]
                    ,submitID = tableID + '-submit'
                    ,submit = layero.find('iframe').contents().find('#'+ submitID);

                //监听提交
                iframeWindow.layui.form.on('submit('+ submitID +')', function(submit){
                    admin.req({
                        url: url
                        , data: submit.field
                        , type: "PUT"
                        , done: function (res) {
                            if (!res.code) {
                                layer.msg(res.message, {icon: 6});
                                obj.update(submit.field);
                            } else {
                                layer.msg(res.message, {icon: 5});
                            }
                            layer.close(index);
                        }
                    });
                });

                submit.trigger('click');
            }
        });
        if (isFull) {
            layer.full(index);
        }
    }

    /**
     * 通用批量删除弹窗
     * @param url
     * @param tableID
     */
    window.batchDel = function (url, tableID) {
        var checkStatus = table.checkStatus(tableID)
            , checkData = checkStatus.data; //得到选中的数据

        if (checkData.length === 0) {
            return layer.msg('请选择数据');
        }

        layer.confirm('确定删除吗？', function (index) {
            admin.req({
                url: url
                , data: {ids: checkData.map(x => {return x.id})}
                , type: "DELETE"
                , done: function (res) {
                    if (res.code === 0) {
                        layer.msg(res.message, {icon: 6});
                        table.reload(tableID);
                        layer.close(index);
                    } else {
                        layer.msg(res.message, {icon: 5});
                    }
                }
            });
        });
    }

    /**
     * 通用删除弹窗
     * @param url
     * @param obj
     */
    window.del = function (url, obj) {
        layer.confirm('真的删除行么', function (index) {
            admin.req({
                url: url
                , type: "DELETE"
                , done: function (res) {
                    if (res.code === 0) {
                        obj.del();
                    }
                    layer.close(index);
                    layer.msg(res.message, {icon: 6})
                }
            });
        });
    }

    /**
     * select动态添加节点
     * @param url 数据接口
     * @param controlid 控件ID
     * @param levels 1为普通下拉框，2为联动下拉框，需将原数据清除
     */
    function addOption(url, controlid, levels) {

        $.get(url, function (result) {
            if (levels === 2) {
                //清除控件的所有值
                $(controlid).empty();
            }
            var data = result.data;
            var str = "";
            for (var i = 0; i < data.length; i++) {
                str += "<option value='" + data[i].id + "'>" + data[i].name + "</option>"
            }
            $(controlid).append(str);
            form.render("select");
        });
    }

    //清楚缓存
    admin.events.clear = function(){
        admin.req({
            url: setter.host + '/user/clear'
            ,type: 'get'
            ,data: {}
            ,done: function(res){
                layer.msg(res.msg, {icon: 6});
            }
        });
    };

    //退出
    admin.events.logout = function () {
        //执行退出接口
        admin.req({
            url: setter.host + '/logout'
            ,type: 'get'
            ,data: {}
            ,done: function(res){ //这里要说明一下：done 是只有 response 的 code 正常才会执行。而 succese 则是只要 http 为 200 就会执行

                //清空本地记录的 token，并跳转到登入页
                admin.exit(function(){
                    location.href = 'admin/login';
                });
            }
        });
    };

    //查看图片
    admin.events.image_preview = function (othis) {
        layer.photos({
            photos: {
                "title": "查看图片" //相册标题
                , "data": [{
                    "src": othis.attr('src') //原图地址
                }]
            }
            , shade: 0.01
            , closeBtn: 1
            , anim: 5
        });
    };

    // 视频预览
    admin.events.video_preview = function (othis) {
        layer.open({
            type: 2
            ,title: '视频预览'
            ,content: 'storage/' + othis.attr('data-id') + '/edit'
            ,maxmin: true
            ,area: ['800px', '600px']
        });
    };

    //选择图片
    admin.events.select_image = function (othis) {
        admin.popup({
            title: '选择图片'
            , area: ['800px', '550px']
            , id: 'LAY-app-attachment-image-select'
            , success: function (layero, index) {
                view(this.id).render('app/attachment/image').done(function () {
                    //图片管理
                    table.render({
                        elem: '#LAY-app-attachment-image'
                        , url: setter.host + '/attachment?file_type=image'
                        , cols: [[
                            {field: 'file_path', title: '图片预览', width: 100, templet: '#imageTpl'}
                            , {field: 'file_name', title: '图片名称'}
                            , {field: 'file_size', width: 90, title: '图片大小'}
                            , {field: 'create_time', width: 160, title: '上传时间'}
                            , {title: '操作', width: 100, align: 'center', fixed: 'right', toolbar: '#table-file-list'}
                        ]]
                        , page: true
                        , limit: 10
                        , limits: [10, 15, 20, 25, 30]
                        , text: '对不起，加载出现异常！'
                    });

                    //监听工具条
                    table.on('tool(LAY-app-attachment-image)', function (obj) {
                        if (obj.event === 'select') {
                            $(othis).prev("div").children("input").val(obj.data.file_path)
                            $(othis).next().remove();
                            $(othis).after('<div><img src="' + obj.data.file_path + '" alt="' + obj.data.file_name +
                                '" style="margin-left:5px;height: 38px;max-width: 38px;"></div>')
                            layer.close(index);
                        }
                    });

                    //上传图片
                    const uploadInst = upload.render({
                        elem: '#LAY-upload-image'
                        , url: setter.host + '/attachment'
                        , accept: 'images'
                        , method: 'post'
                        , acceptMime: 'image/*'
                        , multiple: true
                        , before: function (obj) {
                            //预读本地文件示例，不支持ie8
                            obj.preview(function (index, file, result) {
                               $('#LAY-upload-image-preview').append('<img src="' + result + '" alt="' + file.name + '" style="height: 38px;">')
                            });
                        }
                        ,progress: function(n){
                            element.progress('progress', n + '%');
                        }
                        , done: function (res) {
                            if (res.code > 0) {
                                return layer.msg('上传失败');
                            }
                            layui.table.reload('LAY-app-attachment-image'); //重载表格
                        }
                        , error: function () {
                            const normal = $('#LAY-upload-image-normal');
                            normal.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini image-reload">重试</a>');
                            normal.find('.image-reload').on('click', function () {
                                uploadInst.upload();
                            });
                        }
                    });
                });
            }
        });
    };

    //选择文件
    admin.events.select_file = function (othis) {
        layer.open({
            type: 2
            ,title: '选择文件'
            ,content: '/admin/storage?file_type=file'
            ,maxmin: true
            ,area: ['800px', '550px']
            ,btn: ['确定', '取消']
            ,yes: function(index, layero){
                //文件管理
                table.render({
                    elem: '#LAY-app-attachment-file'
                    , url: 'storage?file_type=file'
                    , cols: [[
                        {field: 'file_path', title: '文件预览', width: 100, templet: '#imgTpl'}
                        , {field: 'file_name', title: '文件名称'}
                        , {field: 'file_size', width: 90, title: '文件大小'}
                        , {field: 'create_time', width: 160, title: '上传时间'}
                        , {title: '操作', width: 100, align: 'center', fixed: 'right', toolbar: '#table-file-list'}
                    ]]
                    , page: true
                    , limit: 10
                    , limits: [10, 15, 20, 25, 30]
                    , text: '对不起，加载出现异常！'
                });

                //监听工具条
                table.on('tool(LAY-app-attachment-file)', function (obj) {
                    if (obj.event === 'select') {
                        $(othis).prev("div").children("input").val(obj.data.file_path)
                        layer.close(index);
                    }
                });

                //上传
                const uploadInst = upload.render({
                    elem: '#LAY-upload-file'
                    , url: 'storage?file_type=file'
                    , accept: 'file'
                    , method: 'post'
                    ,progress: function(n){
                        element.progress('progress', n + '%');
                    }
                    , done: function (res) {
                        if (res.code > 0) {
                            return layer.msg('上传失败');
                        }
                        layui.table.reload('LAY-app-attachment-file'); //重载表格
                    }
                    , error: function () {
                        const normal = $('#LAY-upload-video-normal');
                        normal.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini image-reload">重试</a>');
                        normal.find('.image-reload').on('click', function () {
                            uploadInst.upload();
                        });
                    }
                });


            }
        });
    };

    //选择视频
    admin.events.select_video = function (othis) {
        admin.popup({
            title: '选择视频'
            , area: ['800px', '550px']
            , id: 'LAY-app-attachment-video-select'
            , success: function (layero, index) {
                view(this.id).render('storage/video').done(function () {
                    //图片管理
                    table.render({
                        elem: '#LAY-app-attachment-video'
                        , url: '/admin/storage?file_type=video'
                        , cols: [[
                            {field: 'file_path', title: '视频预览', width: 100, templet: '#imgTpl'}
                            , {field: 'file_name', title: '视频名称'}
                            , {field: 'file_size', width: 90, title: '视频大小'}
                            , {field: 'create_time', width: 160, title: '上传时间'}
                            , {title: '操作', width: 100, align: 'center', fixed: 'right', toolbar: '#table-file-list'}
                        ]]
                        , page: true
                        , limit: 10
                        , limits: [10, 15, 20, 25, 30]
                        , text: '对不起，加载出现异常！'
                    });

                    //监听工具条
                    table.on('tool(LAY-app-attachment-video)', function (obj) {
                        if (obj.event === 'select') {
                            $(othis).prev("div").children("input").val(obj.data.file_path)
                            layer.close(index);
                        }
                    });

                    //上传文件
                    const uploadInst = upload.render({
                        elem: '#LAY-upload-video'
                        , url: 'storage?file_type=video'
                        , accept: 'file'
                        , method: 'post'
                        ,progress: function(n){
                            element.progress('progress', n + '%');
                        }
                        , done: function (res) {
                            if (res.code > 0) {
                                return layer.msg('上传失败');
                            }
                            layui.table.reload('LAY-app-attachment-video'); //重载表格
                        }
                        , error: function () {
                            const normal = $('#LAY-upload-video-normal');
                            normal.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini image-reload">重试</a>');
                            normal.find('.image-reload').on('click', function () {
                                uploadInst.upload();
                            });
                        }
                    });
                });
            }
        });
    };

    //对外暴露的接口
    exports('common', {});
});